package com.insigma.business.qrcode.common.service.impl;

import com.insigma.business.qrcode.common.service.SequenceManager;
import com.insigma.business.qrcode.common.service.SequenceService;
import com.insigma.business.qrcode.common.util.SequenceException;
import com.insigma.business.qrcode.common.vo.SequenceRange;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class SequenceManagerImpl implements SequenceManager {
    private static final Logger logger = LoggerFactory.getLogger(SequenceManagerImpl.class);
    @Resource
    private SequenceService sequenceService;
    private Integer sequenceLength = 8;

    public SequenceManagerImpl() {
    }
    @Override
    public String getNextValue(String sequenceName, String emptyHold) throws SequenceException {
        for(int index = 0; index < this.sequenceService.getRetryTimes(); ++index) {
            try {
                SequenceRange sequenceRange = this.querySequenceRange(sequenceName);
                long value = sequenceRange.getNextValue();
                if (value < sequenceRange.getValue() + sequenceRange.getStep() && value <= sequenceRange.getMax()) {
                    return StringUtils.leftPad(String.valueOf(value), this.sequenceLength, emptyHold);
                }
            } catch (Exception var7) {
                logger.warn(var7.getMessage(), var7);
            }
        }

        throw new SequenceException("获取序列号失败：" + sequenceName + "，重试次数：" + this.sequenceService.getRetryTimes());
    }
    @Override
    public Date getNowDate() {
        return this.sequenceService.getNowDate();
    }

    private SequenceRange querySequenceRange(String sequenceName) {
        try {
            return this.sequenceService.getNextSequenceRange(sequenceName);
        } catch (Exception var3) {
            logger.error("获取序列范围对象失败：", var3);
            throw new SequenceException("获取序列范围对象失败：", var3);
        }
    }

    public void setSequenceService(SequenceService sequenceService) {
        this.sequenceService = sequenceService;
    }

    public void setSequenceLength(Integer sequenceLength) {
        this.sequenceLength = sequenceLength;
    }
}
